package filmring

import java.lang.reflect.Method
import grails.converters.XML
import sun.misc.BASE64Encoder
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import javax.servlet.http.HttpServletRequest

class MovieController {

    def movieService

    /**
     *
     * The action for the website main page
     */
    def index = {
        List<Movie> topMovies =movieService.getTopNMovies(5)
        List<Movie> newReleases =movieService.getNewReleases(5)
        println(newReleases.size()+' '+Movie.list().size())
        FRUser user=null;
        if(session.signedIn==true){
            user = FRUser.get(session.user)
        }
        List<Rating> topRatings = new ArrayList<Rating>()
        List<Rating> newRatings = new ArrayList<Rating>()
        if(user!=null){
            for(Movie movie : topMovies){
                Rating rating = Rating.findByUserAndMovie(user, movie)
                if(rating==null){
                    rating=new Rating(movie:movie, user:user, rating:0)
                }
                topRatings.add(rating)
            }
            for(Movie movie : newReleases){
                Rating rating = Rating.findByUserAndMovie(user, movie)
                if(rating==null){
                    rating=new Rating(movie:movie, user:user, rating:0)
                }
                newRatings.add(rating)
            }
        } else{
            for(Movie movie : topMovies){
                Rating rating = Rating.findByUserAndMovie(user, movie)
                if(rating==null){
                    rating=new Rating(movie:movie, user:[id:0], rating:0)
                }
                topRatings.add(rating)
            }
            for(Movie movie : newReleases){
                Rating rating = Rating.findByUserAndMovie(user, movie)
                if(rating==null){
                    rating=new Rating(movie:movie, user:[id:0], rating:0)
                }
                newRatings.add(rating)
            }
            session.user=0;
        }
        /*System.out.println(topMovies)
        System.out.println(topRatings)
        System.out.println(newReleases)
        System.out.println(newRatings)
        System.out.println(user)
        System.out.println("${topMovies.get(0).ratings} ${topMovies.get(0).ratings.size()}") */
        Movie movie= topMovies.get(0)
        /*
        Netflix api access this may or may not be working properly

         */
        String url = "http://api.netflix.com/catalog/titles"
        String parameters="oauth_consumer_key=rwx5dqkf4nse38555dzs3jxz&oauth_nonce=${(Math.random()*100000000).toLong().toString()}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${(new Date().getTime()/1000).longValue()}&oauth_version=1.0&term=${movie.title.encodeAsURL()}"
        String method ="GET"
        String mykey = "BrX6FxF3p5&";
        //Creates the base string to be encrypted to use as the signature
        String test = method+"&"+url.encodeAsURL()+"&"+parameters.encodeAsURL();

        String enc = null
        try {
            //Encryption code
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
            mac.init(secret);
            byte[] digest = mac.doFinal(test.getBytes());
            enc = new BASE64Encoder().encode(digest);
            enc.encodeAsURL()
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //Creates REST api url
        URL netflix =new URL(url+"?"+parameters+"&oauth_signature="+enc.encodeAsURL())
        String src
        try{
            //Retrieves XML response
            URLConnection connection = netflix.openConnection()
            BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()))
            String result=""
            String decodedString
            // Finds the box art tag
            while((decodedString=input.readLine())!=null){
                if(decodedString.split(" ")[0]=="<box_art"){
                    result=decodedString
                    break;
                }

            }
            input.close()
            //sets src to be the hi res image url
            src=result.split('"')[5]
        }  catch (Exception e){
            //authentication or incorrect url catching sets to default no image available picture
            src="/FilmRing/images/NoImageAvailable.jpg"
        }
        //hard coded image data
        def imagefiles=[Inception:"/FilmRing/images/Inception.jpg",
        "Blue Valentine":"/FilmRing/images/Inception.jpg",
        "No Strings Attached":"/FilmRing/images/NoStringsAttached.jpg",
        "The Social Network":"/FilmRing/images/TheSocialNetwork.jpg",
        "The Big Lebowski":"/FilmRing/images/TheBigLebowski.jpg",
        "The Green Hornet":"/FilmRing/images/TheGreenHornet.jpg",
        "The Life Aquatic with Steve Zissou":"/FilmRing/images/TheLifeAquatic.jpg",
        "The Mechanic":"/FilmRing/images/TheMechanic.jpg",
        "Wall Street":"/FilmRing/images/WallStreet.jpg",
        "Se7en":"/FilmRing/images/Seven.jpg"]
        if(src=="/FilmRing/images/NoImageAvailable.jpg"&&imagefiles.containsKey(movie.title)){
            src=imagefiles.get(movie.title)  //if a hard coded image and netflix failed sets to hard coded
        }
        render(view:"index",model:[movie:movie, topMovies:topMovies, newReleases:topMovies, topRatings:topRatings, newRatings:newRatings, user:user, img:src])
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [movieInstanceList: Movie.list(params), movieInstanceTotal: Movie.count()]
    }

    def show = {
        Movie movie = Movie.get(params.id)
        FRUser user =null
        if(session.user!=null){
            user = FRUser.get(session.user)
        }
        Rating rating = null
        if(user != null){
            rating = Rating.findByUserAndMovie(user, movie)
        }
        if(rating ==null){
            rating=new Rating(movie:movie, user:user, rating:0)
        }
        if(session.user==null){
            session.user=0
        }
        /*
        Netflix api code for additional comments see index action
         */


        String url = "http://api.netflix.com/catalog/titles"
        String parameters="oauth_consumer_key=rwx5dqkf4nse38555dzs3jxz&oauth_nonce=${(Math.random()*100000000).toLong().toString()}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${(new Date().getTime()/1000).longValue()}&oauth_version=1.0&term=${movie.title.encodeAsURL()}"
        String method ="GET"
        String mykey = "BrX6FxF3p5&";
        String test = method+"&"+url.encodeAsURL()+"&"+parameters.encodeAsURL();
        String enc = null
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
            mac.init(secret);
            byte[] digest = mac.doFinal(test.getBytes());
            enc = new BASE64Encoder().encode(digest);
            enc.encodeAsURL()
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        URL netflix =new URL(url+"?"+parameters+"&oauth_signature="+enc.encodeAsURL())
        String src
        try{
            URLConnection connection = netflix.openConnection()
            BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()))
            String result=""
            String decodedString
            while((decodedString=input.readLine())!=null){
                if(decodedString.split(" ")[0]=="<box_art"){
                    result=decodedString
                    break;
                }

            }
            input.close()
            src=result.split('"')[5]
        }  catch (Exception e){
            e.printStackTrace()
            src="/FilmRing/images/NoImageAvailable.jpg"
        }
        def imagefiles=[Inception:"/FilmRing/images/Inception.jpg",
        "Blue Valentine":"/FilmRing/images/Inception.jpg",
        "No Strings Attached":"/FilmRing/images/NoStringsAttached.jpg",
        "The Social Network":"/FilmRing/images/TheSocialNetwork.jpg",
        "The Big Lebowski":"/FilmRing/images/TheBigLebowski.jpg",
        "The Green Hornet":"/FilmRing/images/TheGreenHornet.jpg",
        "The Life Aquatic with Steve Zissou":"/FilmRing/images/TheLifeAquatic.jpg",
        "The Mechanic":"/FilmRing/images/TheMechanic.jpg",
        "Wall Street":"/FilmRing/images/WallStreet.jpg","Se7en":"/FilmRing/images/Seven.jpg"]
        if(src=="/FilmRing/images/NoImageAvailable.jpg"&&imagefiles.containsKey(movie.title)){
            src=imagefiles.get(movie.title)
        }
        println(src)
        render(view: "show", model:[movie:movie, rating:rating, user:user, avgRating:movieService.getAvgRating(movie), img:src])
    }


}
